﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading;
using System.Web;

namespace AuctionHouseDataLibrary
{
    public class RecurringAHScanThread
    {
        private bool _running = true;
        private BackgroundDownloadThread _backgroundDownloadThread;

        public RecurringAHScanThread(BackgroundDownloadThread backgroundDownloadThread)
        {
            _backgroundDownloadThread = backgroundDownloadThread;
        }

        public void Run()
        {
            while (_running)
            {
                using (var context = new ItemDatabaseContext())
                {
                    List<RecurringAHScan> scans = context.RecurringAHScans.ToList();
                    foreach (var recurringAHScan in scans)
                    {
                        if (recurringAHScan.NextRunDateTime <= DateTime.Now)
                        {
                            Globals.Logger.Info(string.Format("Recurring AH Scan Started for realm: {0} d/t: {1}", recurringAHScan.Realm, recurringAHScan.NextRunDateTime));
                            recurringAHScan.LastRunDateTime = recurringAHScan.NextRunDateTime;
                            recurringAHScan.NextRunDateTime = recurringAHScan.NextRunDateTime +
                                                              new TimeSpan(0, 0, recurringAHScan.MinutesBetweenScans, 0);
                            ProcessAHData(recurringAHScan);
                            context.Entry(recurringAHScan).State = EntityState.Modified;
                            context.SaveChanges();
                        }
                    }
                }
                Thread.Sleep(1000);
            }
        }

        private void ProcessAHData(RecurringAHScan recurringAHScan)
        {
            AuctionHouseDataProcessor processor = new AuctionHouseDataProcessor(recurringAHScan.Alliance, recurringAHScan.Horde,
                                                                                recurringAHScan.Neutral, recurringAHScan.Realm,
                                                                                _backgroundDownloadThread);
            bool retry = true;
            int maxRetry = 10;
            int i = 0;
            while (retry && (i < maxRetry))
            {
                retry = !processor.Process();
                i++;
            }
            if (retry)
                Globals.Logger.Error("Unable to process recurring AH scan due to too many errors.");
        }

        public void Stop()
        {
            _running = false;
        }

    }
}